﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WeiXin.Sdk.Common.OAuth;

namespace WeiXin.Sdk.Common.Extensions
{
    /// <summary>
    /// <![CDATA[客服接口]]>
    /// </summary>
    public static class KFClientExtentions
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly static HttpClient httpClient = new HttpClient();

        /// <summary>
        /// <![CDATA[发送客服消息]]>
        /// </summary>
        /// <param name="oAuthClient"></param>
        /// <param name="access_token"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static async Task<string> Send(this IOAuthClient oAuthClient, string access_token, object data)
        {
            string strApiUrl = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", access_token);
            {
                string strJsonData = null;
                if (data is string)
                {
                    strJsonData = Convert.ToString(data);
                }
                else
                {
                    strJsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                }
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strJsonData);
                using (ByteArrayContent byteArray = new ByteArrayContent(buffer))
                {
                    var response = await httpClient.PostAsync(requestUri: strApiUrl, content: byteArray);
                    string strResponseText = await response.Content.ReadAsStringAsync();
                    return strResponseText;
                }
            }
        }

        /// <summary>
        /// <![CDATA[发送客服消息]]>
        /// </summary>
        /// <param name="oAuthClient"></param>
        /// <param name="access_token"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static async Task<string> Send(this IOAuthClient oAuthClient, string access_token, Domain.Sender.KFMessageBase message)
        {
            string strJsonData = Newtonsoft.Json.JsonConvert.SerializeObject(message);
            return await oAuthClient.Send(access_token, strJsonData);
        }
    }
}
